using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Windows.Forms;
using Work.API.Dtos.DrugManagement;
using Work.ErrorCode;

namespace WinFormsApp1.DrugManagement
{
    /// <summary>
    /// 药品查看窗体（用于药品查看模块）
    /// 功能：
    /// 1. 查询和展示药品基础信息
    /// 2. 支持多条件搜索（药品名称、类型、价格范围等）
    /// 
    /// 注意：需要在Designer中添加控件，详见"前端窗体控件说明.md"
    /// </summary>
    public partial class DrugViewForm : Form
    {
        private const string ApiBaseUrl = "http://localhost:5044";
        private readonly HttpClient _httpClient;
        private readonly JsonSerializerOptions _jsonOptions;
        private List<DrugDto> _drugs;

        public DrugViewForm()
        {
            InitializeComponent();
            _httpClient = new HttpClient { BaseAddress = new Uri(ApiBaseUrl) };
            _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
            _drugs = new List<DrugDto>();

            LoadAllDrugs();
        }

        /// <summary>
        /// 加载所有药品
        /// </summary>
        private async void LoadAllDrugs()
        {
            try
            {
                var response = await _httpClient.GetAsync("api/Drug/GetDrugs");
                response.EnsureSuccessStatusCode();
                var json = await response.Content.ReadAsStringAsync();
                var apiResult = JsonSerializer.Deserialize<ApiResult<List<DrugDto>>>(json, _jsonOptions);

                if (apiResult != null && apiResult.Code == ApiEnum.成功 && apiResult.Data != null)
                {
                    _drugs = apiResult.Data;
                    RefreshDataGridView();
                }
                else
                {
                    MessageBox.Show(apiResult?.Message ?? "查询失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载药品列表失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 搜索药品
        /// </summary>
        /// <remarks>
        /// 注意：需要在Designer中添加以下控件：
        /// - txtDrugName (TextBox): 药品名称输入框
        /// - cmbDrugType (ComboBox): 药品类型下拉框
        /// - cmbCostName (ComboBox): 费用名称下拉框
        /// - txtDosageForm (TextBox): 剂型输入框
        /// - txtPurchasePrice (TextBox): 进价输入框
        /// - txtSellingPrice (TextBox): 售价输入框
        /// - btnSearch (Button): 查找按钮
        /// - btnShowAll (Button): 显示全部按钮
        /// - btnClear (Button): 清除按钮
        /// - dgvDrugs (DataGridView): 药品列表表格
        /// </remarks>
        private async void btnSearch_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取控件值（使用FindControl辅助方法）
                var drugName = GetControlText("txtDrugName");
                var drugType = GetControlText("cmbDrugType");
                var costName = GetControlText("cmbCostName");
                var dosageForm = GetControlText("txtDosageForm");
                var purchasePrice = GetControlText("txtPurchasePrice");
                var sellingPrice = GetControlText("txtSellingPrice");

                decimal? minPurchasePrice = null;
                decimal? maxPurchasePrice = null;
                decimal? minSellingPrice = null;
                decimal? maxSellingPrice = null;

                // 解析价格范围（如果有输入）
                // 这里简化处理，实际可以根据需求解析范围

                var url = $"api/Drug/GetDrugs?drugName={Uri.EscapeDataString(drugName ?? "")}" +
                          $"&drugType={Uri.EscapeDataString(drugType ?? "")}" +
                          $"&costName={Uri.EscapeDataString(costName ?? "")}" +
                          $"&dosageForm={Uri.EscapeDataString(dosageForm ?? "")}" +
                          $"&onlyEnabled=true";

                if (minPurchasePrice.HasValue)
                    url += $"&minPurchasePrice={minPurchasePrice.Value}";
                if (maxPurchasePrice.HasValue)
                    url += $"&maxPurchasePrice={maxPurchasePrice.Value}";
                if (minSellingPrice.HasValue)
                    url += $"&minSellingPrice={minSellingPrice.Value}";
                if (maxSellingPrice.HasValue)
                    url += $"&maxSellingPrice={maxSellingPrice.Value}";

                var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();
                var json = await response.Content.ReadAsStringAsync();
                var apiResult = JsonSerializer.Deserialize<ApiResult<List<DrugDto>>>(json, _jsonOptions);

                if (apiResult != null && apiResult.Code == ApiEnum.成功 && apiResult.Data != null)
                {
                    _drugs = apiResult.Data;
                    RefreshDataGridView();
                }
                else
                {
                    MessageBox.Show(apiResult?.Message ?? "查询失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"搜索失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 显示全部药品
        /// </summary>
        private void btnShowAll_Click(object sender, EventArgs e)
        {
            // 清空搜索条件
            SetControlText("txtDrugName", "");
            SetControlText("cmbDrugType", "");
            SetControlText("cmbCostName", "");
            SetControlText("txtDosageForm", "");
            SetControlText("txtPurchasePrice", "");
            SetControlText("txtSellingPrice", "");

            LoadAllDrugs();
        }

        /// <summary>
        /// 刷新数据表格
        /// </summary>
        private void RefreshDataGridView()
        {
            // 注意：需要在Designer中添加名为 dgvDrugs 的DataGridView控件
            // 如果控件名称不同，请修改此处的控件名称
            var dgv = this.Controls.Find("dgvDrugs", true);
            if (dgv.Length > 0 && dgv[0] is DataGridView dataGridView)
            {
                dataGridView.DataSource = null;
                dataGridView.DataSource = _drugs;
                
                // 设置中文列标题
                if (dataGridView.Columns.Count > 0)
                {
                    var columnHeaders = new Dictionary<string, string>
                    {
                        { "DrugId", "药品ID" },
                        { "DrugName", "药品名称" },
                        { "DrugType", "类型" },
                        { "CostName", "费用名称" },
                        { "DosageForm", "剂型" },
                        { "Specification", "规格" },
                        { "PurchasePrice", "进价" },
                        { "SellingPrice", "售价" },
                        { "Inventory", "库存" },
                        { "InventoryUpperLimit", "库存上限" },
                        { "InventoryLowerLimit", "库存下限" },
                        { "Efficacy", "功效" },
                        { "CreateTime", "创建时间" },
                        { "CreateBy", "创建人" },
                        { "UpdateTime", "更新时间" },
                        { "UpdateBy", "更新人" },
                        { "IsEnabled", "是否启用" }
                    };
                    
                    foreach (DataGridViewColumn column in dataGridView.Columns)
                    {
                        if (columnHeaders.ContainsKey(column.Name))
                        {
                            column.HeaderText = columnHeaders[column.Name];
                        }
                        
                        // 格式化进价和售价为两位小数
                        if (column.Name == "PurchasePrice" || column.Name == "SellingPrice")
                        {
                            column.DefaultCellStyle.Format = "F2";
                            column.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// DataGridView数据错误事件处理
        /// </summary>
        private void DgvDrugs_DataError(object? sender, DataGridViewDataErrorEventArgs e)
        {
            // 忽略数据错误，避免显示默认错误对话框
            e.ThrowException = false;
        }

        /// <summary>
        /// 清空所有搜索条件
        /// </summary>
        private void btnClear_Click(object sender, EventArgs e)
        {
            SetControlText("txtDrugName", "");
            SetControlText("cmbDrugType", "");
            SetControlText("cmbCostName", "");
            SetControlText("txtDosageForm", "");
            SetControlText("txtPurchasePrice", "");
            SetControlText("txtSellingPrice", "");
        }

        /// <summary>
        /// 获取控件文本值（辅助方法）
        /// </summary>
        private string GetControlText(string controlName)
        {
            return FormControlHelper.GetControlText(this, controlName);
        }

        /// <summary>
        /// 设置控件文本值（辅助方法）
        /// </summary>
        private void SetControlText(string controlName, string value)
        {
            FormControlHelper.SetControlText(this, controlName, value);
        }

        /// <summary>
        /// 查看记录按钮点击事件（打开药品入库出库记录窗体）
        /// </summary>
        private void BtnViewRecords_Click(object? sender, EventArgs e)
        {
            OpenDrugRecordForm();
        }

        /// <summary>
        /// 药品列表双击事件（打开药品入库出库记录窗体）
        /// </summary>
        private void DgvDrugs_DoubleClick(object? sender, EventArgs e)
        {
            OpenDrugRecordForm();
        }

        /// <summary>
        /// 打开药品入库出库记录窗体
        /// </summary>
        private void OpenDrugRecordForm()
        {
            try
            {
                // 获取当前选中的药品
                var dgv = this.Controls.Find("dgvDrugs", true);
                if (dgv.Length == 0 || !(dgv[0] is DataGridView dataGridView))
                {
                    MessageBox.Show("无法找到药品列表", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 检查是否有选中的行
                if (dataGridView.SelectedRows.Count == 0)
                {
                    MessageBox.Show("请先选择要查看的药品", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 获取选中的药品信息
                var selectedRow = dataGridView.SelectedRows[0];
                if (selectedRow.DataBoundItem is DrugDto drug)
                {
                    // 打开药品入库出库记录窗体
                    var recordForm = new DrugRecordForm(drug);
                    recordForm.ShowDialog(this); // 使用ShowDialog显示为模态窗体
                }
                else
                {
                    MessageBox.Show("无法获取药品信息", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开记录窗体失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

